package com.wit.witmg.interceptor;

import com.wit.witmg.service.ITLogService;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


/**
 * @author bob
 * @date 2018-07-08 20:41
 */
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Resource
    private ITLogService logService;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object){
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();

        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        String openid = httpServletRequest.getHeader("openid");
        String guid = httpServletRequest.getHeader("guid");
        httpServletRequest.setAttribute("openid",openid);
//        httpServletRequest.setAttribute("openid","oDwCp6zr3Qzr2cLmPFEDHbTN4Bgg");
        httpServletRequest.setAttribute("token",token);
        httpServletRequest.setAttribute("guid",guid);

        logService.exceptLog(httpServletRequest,200,"请求");
//
//        //什么都不验证
//        if (method.isAnnotationPresent(PassToken.class)) {
//            return true;
//        }
//
//        String debug = httpServletRequest.getHeader("debug");
//        if(!StringUtils.instance.isEmpty(debug) && debug.equals("147258369")){
//            return true;
//        }
//
//        if (token == null) {
//            throw new RuntimeException("抱歉!无token请重新登录");
//        }
//        //验证token
//        if(openid!=null && openid.length()>0){
//            String rtoken = tokenService.getToken(openid);
//            if (rtoken == null || !rtoken.equals(token)) {
//                throw new RuntimeException("无效token，请重新登录");
//            }
//        }else {
//            throw new RuntimeException("无效token，请重新登录");
//        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
